<!-- <template>
  <img src="@/images/safetyStudy.png" alt="" />
</template>
<script setup lang="ts" name="SafetyStudy"></script>

<style scoped>
img {
  width: calc(100% - 100px);
  display: flex;
  margin-left: 80px;
}
</style> -->
<template>
  <el-form
    :inline="true"
    :model="formInline"
    style="margin-top: 40px; margin-left: 40px"
    class="demo-form-inline"
  >
    <el-form-item label="Experiment Name:">
      <el-input
        v-model="formInline.experiment_name"
        placeholder="input experiment name"
        clearable
        style="width: 200px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="Query"> Query</el-button>
    </el-form-item>
  </el-form>
  <el-form-item style="margin-left: 40px">
    <el-button type="primary" @click="create">Create</el-button>
    <el-button type="danger" @click="batchDelete">Delete</el-button>
  </el-form-item>
  <el-table
    :data="tableData"
    stripe
    head-align="center"
    :cell-style="{ textAlign: 'center' }"
    :header-cell-style="{ 'text-align': 'center' }"
    height="280"
    style="margin-left: 20px; width: calc(100% - 40px)"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column prop="Name" label="Name" width="280" />
    <el-table-column prop="NameEn" label="NameEn" width="320" />
    <el-table-column prop="Description" label="Description" width="320" />
    <el-table-column prop="DescriptionEn" label="DescriptionEn" width="480" />
    <el-table-column
      prop="IfEnabled"
      label="IfEnabled"
      width="100"
      :formatter="ifEnableFormatter"
    >
      <template #default="scope">
        <el-button :class="scope.row.IfEnabled == '1' ? 'pass' : 'noPass'">
          {{ scope.row.IfEnabled == "1" ? "Yes" : "No" }}
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="Operations" width="320">
      <template #default="scope">
        <!-- <el-button
          size="small"
          @click="showRelatedModule(scope.$index, scope.row)"
        >
          edit
        </el-button> -->
        <el-button
          size="small"
          type="primary"
          @click="showRelatedModule(scope.$index, scope.row)"
        >
          related modules
        </el-button>
        <el-button
          size="small"
          type="danger"
          @click="showNeedToLearn(scope.$index, scope.row)"
        >
          need to study
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <ElDivider v-if="relatedModule.length > 0">Related Module</ElDivider>
  <el-table
    :data="relatedModule"
    stripe
    head-align="center"
    :cell-style="{ textAlign: 'center' }"
    :header-cell-style="{ 'text-align': 'center' }"
    height="420"
    style="margin-left: 20px; width: calc(100% - 40px)"
    v-if="relatedModule.length > 0"
  >
    <el-table-column prop="CategoryName" label="CategoryName" width="160" />
    <el-table-column prop="ModuleName" label="ModuleName" width="240" />
    <el-table-column prop="ModuleNameEn" label="ModuleNameEn" width="240" />
    <!-- <el-table-column
      :show-overflow-tooltip="true"
      prop="Description"
      label="Description"
      width="720"
    /> -->
  </el-table>
  <ElDivider v-if="needToLearnModule.length > 0"
    >Need To Learn Module</ElDivider
  >
  <el-table
    :data="needToLearnModule"
    head-align="center"
    :cell-style="{ textAlign: 'center' }"
    :header-cell-style="{ 'text-align': 'center' }"
    height="420"
    style="margin-left: 20px; width: calc(100% - 40px)"
    v-if="needToLearnModule.length > 0"
    :row-class-name="tableRowClassName"
  >
    <el-table-column prop="CategoryName" label="CategoryName" width="120" />
    <el-table-column prop="ModuleName" label="ModuleName" width="150" />
    <el-table-column prop="ModuleNameEn" label="ModuleNameEn" width="150" />
    <el-table-column prop="Content" label="Content" width="420" />
    <el-table-column prop="ContentEn" label="ContentEn" width="420" />
    <!-- <el-table-column prop="Answer" label="Answer" width="150" /> -->
    <!-- <el-table-column prop="Analysis" label="Analysis" width="150" /> -->
    <el-table-column prop="Score" label="Score" width="150" />
    <el-table-column label="Operation" width="120">
      <template #default="{ row }">
        <el-button type="text" @click="showDialog(row, false)">
          View test
        </el-button>
      </template>
    </el-table-column>
    <!-- <el-table-column
      prop="EverOccurredAccident"
      label="EverOccurredAccident"
      width="180"
    /> -->
    <el-table-column
      prop="IfPassed"
      label="IfPassed"
      width="80"
      fixed="center"
      :formatter="ifPassFormatter"
    >
      <template #default="scope">
        <el-button :class="scope.row.ifPass == '1' ? 'pass' : 'noPass'">
          {{ scope.row.ifPass == "1" ? "Yes" : "No" }}
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 浮动表单 -->
  <div class="floating-form" v-if="showForm">
    <div class="form-content">
      <CreateExperiment v-model="showForm" />
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600" center>
    <span>
      <ul class="horizontal-list">
        <li v-for="(item, index) in questionData" :key="index">
          <div style="white-space: pre-wrap">{{ item.ContentEn }}</div>
          <br />
        </li>
      </ul>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="closeDialog"> Close </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="SecurityLearning">
import axios from "axios";
import { ElDivider } from "element-plus";
import { ref, reactive, watch, onMounted } from "vue";
import CreateExperiment from "./CreateExperiment.vue";
import api from "@/utils/axiosInstance";
import { ElMessage } from "element-plus";
import { dialogContentEmits } from "element-plus/es/components/dialog/src/dialog-content.mjs";

let dialogVisible = ref(false);
let dialogTitle = ref();
let experimentLoading = ref(false);
let relatedModuleLoading = ref(false);
let needToLearnModuleLoading = ref(false);
let tableData = ref([]);
let relatedModule = ref([]);
let needToLearnModule = ref([]);
// questions
let questionData = ref([]);
const formInline = reactive({
  experiment_name: "",
});

function showDialog(row: any, value: boolean) {
  dialogTitle.value = row.ModuleNameEn + "'s Test Question";
  api
    .post("/experiment/module-test", { module_id: row.Id })
    .then((response) => {
      console.log(response.data, "data");
      questionData.value = response.data;
      dialogVisible.value = true;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
    })
    .finally(() => {});
}

function closeDialog() {
  dialogVisible.value = false;
}

// 监听选择
interface TableItem {
  Id: string; // 注意大小写，根据你的实际数据结构调整
  // 其他属性...
}
const selectable = (row: any) => ![1, 2].includes(row.id);
let deleteIds = ref<string[]>([]);
function handleSelectionChange(val: TableItem[]) {
  for (let i = 0; i < val.length; i++) {
    deleteIds.value.push(val[i].Id);
  }
}

// about form
let showForm = ref(false);
// 监听子组件值的变化
watch(showForm, (newVal, oldVal) => {
  console.log("子组件值变化:", oldVal, "→", newVal);
});

onMounted(() => {
  Query();
});

const Query = () => {
  console.log("submit!");
  experimentLoading.value = true;

  api
    .post("/experiment/query", formInline)
    .then((response) => {
      tableData.value = response.data;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
    })
    .finally(() => {
      experimentLoading.value = false;
    });
};

function showRelatedModule(index: any, row: any) {
  let params = { id: row.Id, name: row.Name };
  relatedModuleLoading.value = true;
  api
    .post("/experiment/related-module", params)
    .then((response) => {
      relatedModule.value = response.data;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
    })
    .finally(() => {
      relatedModuleLoading.value = false;
    });
}

function showNeedToLearn(index: any, row: any) {
  let params = { id: row.Id, name: row.Name };
  needToLearnModuleLoading.value = true;
  api
    .post("/experiment/need-to-learn-module", params)
    .then((response) => {
      needToLearnModule.value = response.data;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
    })
    .finally(() => {
      needToLearnModuleLoading.value = false;
    });
}

function ifPassFormatter(row: any, column: any) {
  if (row.IfPass == "1") {
    return "Yes";
  } else {
    return "No";
  }
}

function ifEnableFormatter(row: any, column: any) {
  if (row.IfEnabled == "1") {
    return "Yes";
  } else {
    return "No";
  }
}

function create() {
  showForm.value = true;
}

function batchDelete() {
  console.log("submit!");
  experimentLoading.value = true;

  api
    .post("/experiment/delete", { ids: deleteIds.value })
    .then((response) => {
      console.log(response, "response");
      if (response.status == 200) {
        ElMessage({
          message: "Successfully deleted selected experiment infomations!",
          type: "success",
        });
      } else {
        ElMessage({
          message: "Failed to delete selected experiment infomations!",
          type: "error",
        });
      }
    })
    .catch((error) => {
      // 处理错误
      ElMessage({
        message: "Failed to delete selected experiment infomations!",
        type: "error",
      });
      console.log(error, "error");
    })
    .finally(() => {
      experimentLoading.value = false;
      Query();
    });
}

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  if (row.EverOccurredAccident === "1") {
    return "warning-row";
  } else {
    return "green-row";
  }
};
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 280px;
}
.demo-form-inline .el-select {
  --el-select-width: 280px;
}
.pass,
.occurred {
  text-decoration: underline;
  background-color: #70c546;
  border-style: solid;
  border-radius: 5px;
  /* border-width: 3px; */
  border-color: #70c546;
}
.noPass,
.noOccurred {
  background-color: #f56c6c;
  border-style: solid;
  border-radius: 5px;
  border-width: 4px;
  border-color: #f56c6c;
}
.modal {
  width: 200px;
  height: 150px;
  background-color: skyblue;
  border-radius: 10px;
  padding: 5px;
  box-shadow: 0 0 5px;
  text-align: center;
  position: fixed;
  left: 50%;
  top: 20px;
  margin-left: -100px;
}

.floating-form {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.form-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 720px;
  height: 540px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.el-table .warning-row {
  background-color: rgba(240, 5, 5, 0.1);
}
.el-table .green-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-table tbody tr:hover > td {
  background-color: unset !important;
}

/* 
单元格识别换行
.el-table .cell.el-tooltip {
  white-space: pre-wrap;
} */
</style>
